import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

public class MessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        IMessage iMessage = new IMessage();
        iMessage.setType(MessageTypeEnum.get(byteBuf.readByte()));
        int fromLength = byteBuf.readInt();
        CharSequence from = byteBuf.readCharSequence(fromLength, Charset.defaultCharset());
        iMessage.setFrom(from.toString());
        int toLength = byteBuf.readInt();
        CharSequence to = byteBuf.readCharSequence(toLength, Charset.defaultCharset());
        iMessage.setTo(to.toString());
        int bodylength = byteBuf.readInt();
        CharSequence body = byteBuf.readCharSequence(bodylength, Charset.defaultCharset());
        iMessage.setBody(body.toString());
        list.add(iMessage);
    }
}
